//
// Created by work on 24-6-25.
//

#include <server/CUserApi.h>
#include <os/miscellany/stddef.h>
#include <iot_model_device/device_model_mgr/CUserMgr.h>
namespace iotplat
{
    CUserApi::CUserApi()
    {

    }

    void CUserApi::start() {
        userRegister();
        userLogin();
    }

    void CUserApi::userRegister() {
        CROW_ROUTE(CSimpleAppSingleton::getInstance(), "/api/userMgr/userRegister").methods("POST"_method)([](const crow::request& req, crow::response& res) {
            Json::CharReaderBuilder builder;
            Json::CharReader* reader = builder.newCharReader();
            Json::Value json;
            JSONCPP_STRING errs;
            if (!reader->parse(req.body.c_str(), req.body.c_str() + req.body.length(), &json, &errs)) {
                REPLY_FAILED_REQUEST( std::string("请求解析失败，请检查Json请求体!"+errs));
            }

            Json::Value jsonres = CUserMgr::ins().userRegister(json);
            res.set_header("Content-Type", "application/json");
            res.body = jsonres.toStyledString().c_str();
            res.end();
        });
    }

    void CUserApi::userLogin() {
        CROW_ROUTE(CSimpleAppSingleton::getInstance(), "/api/userMgr/userLogin").methods("POST"_method)([](const crow::request& req, crow::response& res) {
            Json::Value body;
            do {
                Json::CharReaderBuilder builder;
                Json::CharReader* reader = builder.newCharReader();
                JSONCPP_STRING errs;
                if (!reader->parse(req.body.c_str(), req.body.c_str() + req.body.length(), &body, &errs)) {
                    REPLY_FAILED_REQUEST(std::string("请求解析失败，请检查Json请求体!"+errs));
                }
            } while(0);
            Json::Value jsonres = CUserMgr::ins().userLogin(body);
            res.set_header("Content-Type", "application/json");
            res.body = jsonres.toStyledString().c_str();
            res.end();
        });
    }
}
